package com.wzh.sending.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.wzh.sending.callback.LocationInterface;
import com.wzh.sending.info.LocationInfo;
import com.wzh.sending.info.PhoneInfo;
import com.wzh.sending.info.UsersInfo;
import com.wzh.sending.utils.LocationUtil;
import com.wzh.sending.utils.Utils;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Hu on 2016/8/29.
 */
public class MyService extends Service {
    LocationInfo locationInfo;
    UsersInfo usersInfo;
    PhoneInfo phoneInfo;
    double lot = 0;
    double lat = 0;
    SharedPreferences preferences;
    LocationUtil locationUtil;
    Handler handler;
    Runnable runnable;

    @Override
    public void onCreate() {
        super.onCreate();
        initView();
        Log.e("onCreate", "onCreate");
    }

    private void initView() {
        preferences = getBaseContext().getSharedPreferences("loc", Context.MODE_PRIVATE);
        handler = new Handler();
        locationInfo = new LocationInfo();
        usersInfo = new UsersInfo();
        phoneInfo = new PhoneInfo(getBaseContext());
        locationUtil = new LocationUtil(getBaseContext());
        locationUtil.initLocation();
        locationUtil.setLocationInterface(new LocationInterface() {
            @Override
            public void getLocation(AMapLocation loc) {
                getJiexi(loc);
                Log.e("地址", loc.getAddress());
            }
        });
        runnable = new Runnable() {
            @Override
            public void run() {
                if (locationUtil != null) {
                    locationUtil.startLocation();
                    handler.postDelayed(this, 200000);
//                    handler.postDelayed(this, 4000);
                }
            }
        };
        handler.post(runnable);
    }

    private void getJiexi(final AMapLocation loc) {
        if (null != loc) {
            locationUtil.stopLocation();
            //解析定位结果
            if (loc.getLongitude() != lot || loc.getLatitude() != lat) {
                if (locationInfo == null) {
                    locationInfo = new LocationInfo();
                }
                if (TextUtils.isEmpty(loc.getAddress())) {
                    locationInfo.setAddRess(loc.getCity());
                } else {
                    locationInfo.setAddRess(loc.getAddress());
                }
                locationInfo.setImeiNo(phoneInfo.getImeiNo());
                locationInfo.setLineNo(phoneInfo.getNativePhoneNumber());
                locationInfo.setLongitude(loc.getLongitude());
                locationInfo.setLatitude(loc.getLatitude());
                locationInfo.setSpeed(loc.getSpeed());

                locationInfo.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {
                            Log.e("创建数据成功：", s);
                            lot = loc.getLongitude();
                            lat = loc.getLatitude();
                            savaUser(loc);
                        } else {
                            Log.e("error：", e.getMessage());
                        }
                    }
                });

            } else {
                Log.e("创建数据成功：", "重复数据");
            }

        }
    }

    private void savaUser(final AMapLocation loc) {
        BmobQuery<UsersInfo> query = new BmobQuery<UsersInfo>();
        query.addWhereEqualTo("imeiNo", phoneInfo.getImeiNo());
        query.findObjects(new FindListener<UsersInfo>() {
            @Override
            public void done(List<UsersInfo> list, BmobException e) {
                Log.e("list", list.size() + "");
                if (e == null) {
                    if (list.size() == 0) {
                        if (usersInfo == null) {
                            usersInfo = new UsersInfo();
                        }
                        usersInfo.setName("暂无姓名");
                        usersInfo.setLineNo(phoneInfo.getNativePhoneNumber());
                        usersInfo.setImeiNo(phoneInfo.getImeiNo());
                        usersInfo.setLat(loc.getLatitude());
                        usersInfo.setLot(loc.getLongitude());
                        usersInfo.setAddRess(TextUtils.isEmpty(loc.getAddress()) ? loc.getCity() : loc.getAddress());
                        usersInfo.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null) {

                                    Log.e("新用户：", s);
                                } else {
                                    Log.e("error：", e.getMessage());
                                }
                            }
                        });

                    } else if (list.size() == 1) {
                        usersInfo.setLat(loc.getLatitude());
                        usersInfo.setLot(loc.getLongitude());
                        usersInfo.setAddRess(loc.getAddress());
                        usersInfo.update(list.get(0).getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {

                            }
                        });


                    }

                }

            }
        });
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("onStartCommand", "onStartCommand");
        Log.e("locetion", (locationUtil == null) + "");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.e("onStart", "onStart");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy", "onDestroy");
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        locationUtil.stopLocation();
        locationUtil.destroyLocation();
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
